# This controller handles the login/logout function of the site.  
class SessionsController < ApplicationController
  layout 'login'
  include ApplicationHelper

  # render new.rhtml
  def new
  end

  def create
    if using_open_id?
      openid_authentication
    else
      normal_login(params[:login], params[:password], params[:remember_me])
    end
  end
    

  def destroy
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "You have been logged out"
    redirect_back_or_default(home_path)
  end
  
  def use_openid
    render :partial => 'openid_login'
  end
  
  def use_normal_login
    render :partial => 'normal_login'
  end
  
  # Authentication using normal Login
  def normal_login(login, password, remember_me)
    self.current_user = User.authenticate(login, password)
    if logged_in?
      if remember_me == "1"
        current_user.remember_me unless current_user.remember_token?
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
      end
      successful_login
    else
	    failed_login "Sorry, you can't enter"
    end
  end

  # Authentication using OpenID
  def openid_authentication
    authenticate_with_open_id(params[:openid_url], :required => [:fullname, :email]) do |result, identity_url|
	  if result.successful?
	    if self.current_user = User.find_or_create_by_identity_url(identity_url)
          successful_login
		else
		  failed_login "Sorry, no user by that identity URL exists (#{identity_url})"
		end
	  else
		failed_login result.message
	  end
	end
  end
  
  
  private
  
  def successful_login
    flash[:notice] = "Welcome. Logged in successfully"
    redirect_back_or_default(home_path)
  end
  
  def failed_login(message)
    flash[:error] = message
    redirect_back_or_default(home_path)
  end
end
